package com.exam.classes.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.exam.classes.service.ClassesService;
import com.exam.classes.service.StudentService;
import com.exam.common.entity.Request;
import com.exam.common.entity.StatusCode;
import com.exam.common.exception.ExamException;
import com.sun.org.apache.regexp.internal.RE;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @ClassName : StudentController
 * @Description :
 * @Author : WHB
 */

@RestController
@Api(description = "学生Api接口")
public class StudentController {

    @Autowired
    private StudentService studentService;
    
    @Autowired 
    private ClassesService classesService;

    @PostMapping("/student")
    @ApiOperation(value = "加入班级",notes = "加入班级")
    public Request joinClasses(@RequestBody String data){

        JSONObject jsonObject = JSON.parseObject(data);
        String joinKey = jsonObject.get("joinKey").toString();
        Long sid = Long.valueOf(jsonObject.get("sid").toString());

        try {
            //通过joinKey查找班级ID
            int classId = classesService.queryClassesByKey(joinKey);
            System.out.println(classId);
            //查找班级失败
            if (classId == 0){
                return new Request(false, StatusCode.ERROR,"验证码错误");
            }else {
                //加入班级
                studentService.joinClasses(sid,classId);
                return new Request(true, StatusCode.OK,"加入班级成功");
            }
        }catch (ExamException e){
            System.out.println(e);
            return new Request(false, StatusCode.ERROR,"加入班级失败");
        }
    }

}
